<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="utf-8">
    <title>精英杂志 - 管理后台</title>
    <link href="/vendor/bootstrap-lite.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/easymde@2.18.0/dist/easymde.min.css" rel="stylesheet">
    <link href="/css/custom.css" rel="stylesheet">
    <style>
        .upload-area {
            border: 2px dashed #ccc;
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-bottom: 20px;
        }
        .upload-area:hover {
            border-color: #007bff;
            background-color: #f8f9fa;
        }
        .upload-area.dragover {
            border-color: #28a745;
            background-color: #f8fff9;
        }
        .upload-preview {
            max-width: 100%;
            max-height: 200px;
            margin: 10px 0;
            border-radius: 4px;
        }
        .progress {
            margin-top: 10px;
        }
        .image-gallery {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
            gap: 10px;
            margin-top: 15px;
            max-height: 200px;
            overflow-y: auto;
        }
        .gallery-item {
            position: relative;
            border-radius: 4px;
            overflow: hidden;
            cursor: pointer;
        }
        .gallery-item img {
            width: 100%;
            height: 80px;
            object-fit: cover;
        }
        .gallery-item .delete-btn {
            position: absolute;
            top: 2px;
            right: 2px;
            background: rgba(220, 53, 69, 0.8);
            color: white;
            border: none;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            font-size: 12px;
            cursor: pointer;
            opacity: 0;
            transition: opacity 0.2s;
        }
        .gallery-item:hover .delete-btn {
            opacity: 1;
        }
        .insert-buttons {
            margin-top: 10px;
        }
        .insert-buttons button {
            margin-right: 10px;
            margin-bottom: 5px;
        }
    </style>
</head>
<body>
    <div class="container py-5">
        <h1 class="mb-4">📰 文章管理</h1>
        
        <!-- 图片上传区域 -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0">🖼️ 图片管理</h5>
            </div>
            <div class="card-body">
                <div class="upload-area" id="uploadArea">
                    <div id="uploadPrompt">
                        <i class="fas fa-cloud-upload-alt fa-2x mb-2"></i>
                        <p>点击选择图片或拖拽图片到此处</p>
                        <small class="text-muted">支持 JPG、PNG、GIF 格式，最大 5MB</small>
                    </div>
                    <input type="file" id="fileInput" accept="image/*" style="display: none;" multiple>
                    <div id="uploadPreview"></div>
                    <div class="progress" id="uploadProgress" style="display: none;">
                        <div class="progress-bar" role="progressbar" style="width: 0%"></div>
                    </div>
                </div>
                
                <div class="image-gallery" id="imageGallery"></div>
                
                <div class="insert-buttons">
                    <button class="btn btn-sm btn-outline-primary" onclick="insertImageMarkdown()">插入图片</button>
                    <button class="btn btn-sm btn-outline-secondary" onclick="refreshGallery()">刷新图库</button>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-8">
                <form id="articleForm">
                    <div class="mb-3">
                        <label class="form-label">文章标题</label>
                        <input type="text" class="form-control" id="title" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">文章内容 (Markdown)</label>
                        <textarea id="content" class="form-control" rows="15"></textarea>
                    </div>
                    <button type="submit" class="btn btn-primary">发布文章</button>
                    <button type="button" class="btn btn-outline-secondary" onclick="location.reload()">刷新列表</button>
                </form>
            </div>
            
            <div class="col-md-4">
                <h5>文章列表</h5>
                <div id="articleList" class="list-group"></div>
            </div>
        </div>
    </div>

    <script src="/vendor/bootstrap-lite.min.js"></script>
    <script src="/js/gitee-config.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/easymde@2.18.0/dist/easymde.min.js"></script>
    <script>
        const easyMDE = new EasyMDE({ 
            element: document.getElementById('content'),
            spellChecker: false,
            status: ['lines', 'words']
        });
        
        // 图片上传相关功能
        const uploadArea = document.getElementById('uploadArea');
        const fileInput = document.getElementById('fileInput');
        const uploadPreview = document.getElementById('uploadPreview');
        const uploadProgress = document.getElementById('uploadProgress');
        const imageGallery = document.getElementById('imageGallery');
        
        // 点击上传区域触发文件选择
        uploadArea.addEventListener('click', () => fileInput.click());
        
        // 拖拽上传
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });
        
        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('dragover');
        });
        
        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            const files = Array.from(e.dataTransfer.files);
            handleFiles(files);
        });
        
        // 文件选择处理
        fileInput.addEventListener('change', (e) => {
            const files = Array.from(e.target.files);
            handleFiles(files);
        });
        
        // 处理文件上传
        function handleFiles(files) {
            const imageFiles = files.filter(file => file.type.startsWith('image/'));
            
            if (imageFiles.length === 0) {
                alert('请选择图片文件');
                return;
            }
            
            imageFiles.forEach(file => {
                if (file.size > 5 * 1024 * 1024) {
                    alert(`文件 ${file.name} 超过5MB限制`);
                    return;
                }
                uploadFile(file);
            });
        }
        
        // 上传单个文件
        function uploadFile(file) {
            const formData = new FormData();
            formData.append('image', file);
            
            uploadProgress.style.display = 'block';
            uploadProgress.querySelector('.progress-bar').style.width = '0%';
            
            // 模拟上传进度
            let progress = 0;
            const progressInterval = setInterval(() => {
                progress += Math.random() * 20;
                if (progress > 90) {
                    clearInterval(progressInterval);
                }
                uploadProgress.querySelector('.progress-bar').style.width = progress + '%';
            }, 200);
            
            fetch('/api/upload-image', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                clearInterval(progressInterval);
                uploadProgress.querySelector('.progress-bar').style.width = '100%';
                
                setTimeout(() => {
                    uploadProgress.style.display = 'none';
                    if (data.success) {
                        showPreview(data.imageUrl);
                        refreshGallery();
                        alert('图片上传成功！');
                    } else {
                        alert('上传失败: ' + data.message);
                    }
                }, 500);
            })
            .catch(error => {
                clearInterval(progressInterval);
                uploadProgress.style.display = 'none';
                alert('上传出错: ' + error.message);
            });
        }
        
        // 显示上传预览
        function showPreview(imageUrl) {
            uploadPreview.innerHTML = `
                <img src="${imageUrl}" class="upload-preview" alt="预览">
                <p class="text-muted mt-2">上传成功！点击图片插入到编辑器</p>
            `;
            uploadPreview.querySelector('img').addEventListener('click', () => {
                insertImageToEditor(imageUrl, '上传的图片');
            });
        }
        
        // 刷新图库
        function refreshGallery() {
            fetch('/api/images')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayGallery(data.images);
                    }
                })
                .catch(error => {
                    console.error('获取图片列表失败:', error);
                });
        }
        
        // 显示图片库
        function displayGallery(images) {
            imageGallery.innerHTML = images.map(image => `
                <div class="gallery-item" onclick="insertImageToEditor('${image.url}', '${image.name}')">
                    <img src="${image.url}" alt="${image.name}">
                    <button class="delete-btn" onclick="deleteImage(event, '${image.url}')">×</button>
                </div>
            `).join('');
        }
        
        // 插入图片到编辑器
        function insertImageToEditor(imageUrl, altText) {
            const markdown = `![${altText}](${imageUrl})\n\n`;
            const cursor = easyMDE.codemirror.getCursor();
            easyMDE.codemirror.replaceRange(markdown, cursor);
            easyMDE.codemirror.focus();
        }
        
        // 插入图片按钮功能
        function insertImageMarkdown() {
            const markdown = '![图片描述](图片URL)\n\n';
            const cursor = easyMDE.codemirror.getCursor();
            easyMDE.codemirror.replaceRange(markdown, cursor);
            easyMDE.codemirror.focus();
        }
        
        // 删除图片
        function deleteImage(event, imageUrl) {
            event.stopPropagation();
            if (confirm('确定要删除这张图片吗？')) {
                fetch('/api/delete-image', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ imageUrl: imageUrl })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        refreshGallery();
                        alert('图片删除成功');
                    } else {
                        alert('删除失败: ' + data.message);
                    }
                })
                .catch(error => {
                    alert('删除出错: ' + error.message);
                });
            }
        }
        
        // 文章管理功能
        function loadArticles() {
            fetch('/index.json')
                .then(r => r.json())
                .then(data => {
                    const list = document.getElementById('articleList');
                    list.innerHTML = data.map(item => `
                        <div class="list-group-item d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="mb-1">${item.title}</h6>
                                <small class="text-muted">${new Date(item.date).toLocaleDateString()}</small>
                            </div>
                            <button class="btn btn-sm btn-outline-danger" onclick="deleteArticle('${item.permalink}')">删除</button>
                        </div>
                    `).join('');
                })
                .catch(() => {
                    document.getElementById('articleList').innerHTML = 
                        '<div class="alert alert-info">暂无文章，先发布一篇吧！</div>';
                });
        }
        
        // 发布文章
        document.getElementById('articleForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const title = document.getElementById('title').value;
            const content = easyMDE.value();
            const slug = title.toLowerCase().replace(/[^\w\u4e00-\u9fa5]+/g, '-');
            const date = new Date().toISOString().split('T')[0];
            
            const frontMatter = `---\ntitle: "${title}"\ndate: ${date}\ndraft: false\n---\n\n`;
            const markdown = frontMatter + content;
            
            // 创建下载
            const blob = new Blob([markdown], { type: 'text/markdown' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `${slug}.md`;
            a.click();
            
            alert('文章已生成，请将文件放入 content/posts 目录并重新部署');
            this.reset();
            easyMDE.value('');
        });
        
        // 删除文章
        function deleteArticle(permalink) {
            if(confirm('确定删除？请手动删除 content/posts 中的对应文件并重新部署。')) {
                alert('请手动删除文件后重新部署');
            }
        }
        
        // 页面加载时执行
        loadArticles();
        refreshGallery();
    </script>
</body>
</html>